<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\ThirdOrder;
use app\common\model\UserQq;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;

/**
 * 奖品兑换
 */
class ExPrize extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedBind = ['qq'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 兑换请求
     */
    public function send(){
        $ex_order_sn = $this->request->post('third_order_sn');
        if(!$ex_order_sn){
            $this->error(__('Invalid parameters'));
        }

        //查询订单是否已经录入
        $thirdOrder = ThirdOrder::where('third_order_sn',$ex_order_sn)->find();
        if(!$thirdOrder){
            $this->error(__('No results were found'));
        }

        //已经兑换过了
        if($thirdOrder['ex_status']){
            $this->error(__('Order is use'));
        }

        //入库
        try {
            $data = [
                'user_id'   => $this->auth->id ?? 0,
                'ex_order_sn'   => $ex_order_sn,
                'ex_order_id'   => $thirdOrder['id']
            ];
            \app\common\model\Exprize::create($data);
            ThirdOrder::where('id',$thirdOrder['id'])->update(['ex_status'=>1,'usetime'=>time()]);

        }catch (Exception $e)
        {
            $this->error(__('Operation failed').$e->getMessage());
        }
        $this->success(__('Operation completed'));
    }

    /**
     * 订单记录
     */
    public function getList(){

    }

    /**
     * 录入QQ
     */
    public function qq(){
        $qq = $this->request->post('qq');
        if(!$qq){
            $this->error(__('Invalid parameters'));
        }

        $qInfo = UserQq::where('qq',$qq)->find();
        if($qInfo){
            $this->error(__('Data already exists'));
        }

        $count = UserQq::where('user_id', $this->auth->id)->find();
        if($count){
            $this->error(__('Data already exists'));
        }

        $data = [
            'user_id'   => $this->auth->id ,
            'qq'        => $qq,
        ];
        UserQq::create($data);

        $this->success(__('Operation completed'));
    }

}
